package com.mifengs.mall.ui.web;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mifengs.commonbase.util.LogUtil;
import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.commonbase.util.StatusBarCompat;
import com.mifengs.commonbase.util.StatusBarUtils;
import com.mifengs.mall.R;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.mall.util.Tools;
import com.tencent.android.tpush.XGPushClickedResult;
import com.tencent.android.tpush.XGPushManager;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.ShareBoard;
import com.umeng.socialize.shareboard.ShareBoardConfig;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.Log;
import com.umeng.socialize.utils.ShareBoardlistener;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class CommonWebActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks{

    private static final String TAG = "CommonWebViewActivity";
    public static final String ExtraWebPath = "ExtraWebPath";
    public static final String ExtraWebTitle = "ExtraWebTitle";
    public static final int REQUEST_PERMISSION_STORAGE = 3;
    public static final int REQUEST_PERMISSION_CAMERA = 6;
    public static final int PERMISSION_READ_WRITE_EXTERNAL_STORAGE = 7;
    private String mPath="";
    private String mTitle="";
    private WebFragment mWebFragment;
    private Fragment mCurrentFragment;
    private UMShareListener mShareListener;
    private ShareAction mShareAction;
    private boolean isShare;
    private TextView mTvTitle;
    private Boolean isGoodsShare =false;
    private String shareTopText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_common_web);
        mTvTitle = (TextView) this.findViewById(R.id.tv_title);
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this,R.color.nav_color));
        StatusBarUtils.StatusBarLightMode(this);
        XGPushClickedResult clickedResult = XGPushManager.onActivityStarted(this);
        if(clickedResult!=null){
            //获取消息附近参数
            String  ster= clickedResult.getCustomContent();
            //获取消息标题
            String  set = clickedResult.getTitle();
            //获取消息内容
            String  s= clickedResult.getContent();
            LogUtil.i("Tpush:",ster+" "+ set + " " + s);
            if(!TextUtils.isEmpty(ster)){
                try {
                    JSONObject jsonObject = new JSONObject(ster);
                    mPath = jsonObject.optString("actionUrl");
                    mTitle = jsonObject.optString("title");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }else{
            Intent intent = this.getIntent();
            mPath = intent.getStringExtra(ExtraWebPath);
            mTitle = intent.getStringExtra(ExtraWebTitle);
        }
        mWebFragment = WebFragment.newInstance(mPath,mTitle);
        mCurrentFragment = mWebFragment;
        if (savedInstanceState == null) {
            FragmentTransaction ft = this.getSupportFragmentManager().beginTransaction();
            ft.add(R.id.container, mCurrentFragment).commit();
        }
        initNavigationBar();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mWebFragment.onActivityResult(requestCode,resultCode,data);
        if(isShare) UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebFragment.canGoBack()) {
            mWebFragment.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    public void setTitle(String title){
        if(mTvTitle!=null){
            mTvTitle.setText(title);
        }
    }


    public void setShare(final String url, final String img, final String prod, final int type, final String title, final boolean isComShare, String shareTopStr){
        shareTopText = shareTopStr;
        isGoodsShare = isComShare;
        TextView tvShare = getTextView();
        tvShare.setVisibility(View.VISIBLE);

        isShare = true;
        tvShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readWritePermissions();
            }
        });

        mShareListener = new CommonWebActivity.CustomShareListener(this);
        /*增加自定义按钮的分享面板*/
        mShareAction = new ShareAction(CommonWebActivity.this).setDisplayList(
                SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,
                SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE,
                SHARE_MEDIA.SMS,SHARE_MEDIA.EMAIL)
                .addButton("umeng_sharebutton_copyurl", "umeng_sharebutton_copyurl", "umeng_socialize_copyurl", "umeng_socialize_copyurl")
                .setShareboardclickCallback(new ShareBoardlistener() {
                    @Override
                    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                        if (snsPlatform.mShowWord.equals("umeng_sharebutton_copyurl")) {
                            Tools.copy(url,CommonWebActivity.this);
                            Toast.makeText(CommonWebActivity.this, "复制成功", Toast.LENGTH_LONG).show();
                        } else {
                            if (share_media == SHARE_MEDIA.SMS) {
                                new ShareAction(CommonWebActivity.this).withText(url)
                                        .setPlatform(share_media)
                                        .setCallback(mShareListener)
                                        .share();
                            } else {
                                String photoUrl = PreferenceUtils.getPhotoUrl(getContext());
                                UMWeb web = new UMWeb(url);
                                if(type ==1){
                                    web.setTitle("蜜蜂商城蜂巢");
                                    web.setDescription("蜜蜂商城蜂巢是一款线上与线下相结合的新零售APP，为用户带来更便捷、更快速、更放心的购物体验，同时提供共享雨伞、共享充电宝等共享服务，为门店引流，助力全国百万家实体门店。");
                                    web.setThumb(new UMImage(CommonWebActivity.this, R.drawable.share_logo));
                                }else{
                                    if(TextUtils.isEmpty(title)){
                                        web.setTitle("蜜蜂商城蜂巢");
                                    }else{
                                        web.setTitle(title);
                                    }

                                    web.setDescription(prod);
                                    if(!TextUtils.isEmpty(img)){
                                       if("http".equals(img.substring(0,4))){
                                            web.setThumb(new UMImage(CommonWebActivity.this,img));
                                        }else{
                                            web.setThumb(new UMImage(CommonWebActivity.this,photoUrl+img));
                                        }

                                    }else{
                                        web.setThumb(new UMImage(CommonWebActivity.this,R.drawable.share_logo));
                                    }
                                }
                                new ShareAction(CommonWebActivity.this).withMedia(web)
                                        .setPlatform(share_media)
                                        .setCallback(mShareListener)
                                        .share();
                            }
                        }
                    }
                });
        //1表示是我的分享  2表示是在抢购订单的分享
        if(type==2){
            readWritePermissions();
        }else{
            tvShare.setText("分享");
        }
    }


    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        switch (requestCode) {
            case REQUEST_PERMISSION_CAMERA:
                mWebFragment.onActivityNoBack();
                break;
            case PERMISSION_READ_WRITE_EXTERNAL_STORAGE:
               final Dialog permissionsDialog = new Dialog(this,R.style.dialog);
                permissionsDialog.setContentView(R.layout.dialog);
                TextView tvInfo = (TextView) permissionsDialog.findViewById(R.id.tv_info);
                TextView tvTitle= (TextView) permissionsDialog.findViewById(R.id.tv_title);
                Button btOk = (Button)permissionsDialog.findViewById(R.id.bt_ok);
                tvInfo.setText("需要开启读写权限后才能使用");
                tvTitle.setText("权限申请");
                btOk.setText("去设置");
                permissionsDialog.findViewById(R.id.bt_cancle).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        permissionsDialog.dismiss();
                    }
                });
                permissionsDialog.findViewById(R.id.bt_ok).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent= Tools.getAppDetailSettingIntent(getContext());
                        startActivity(intent);
                        permissionsDialog.dismiss();
                    }
                });
                permissionsDialog.show();
                break;
        }
    }


    private static class CustomShareListener implements UMShareListener {

        private WeakReference<CommonWebActivity> mActivity;

        private CustomShareListener(CommonWebActivity activity) {
            mActivity = new WeakReference(activity);
        }

        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {

            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(mActivity.get(),  " 收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
                if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                        && platform != SHARE_MEDIA.EMAIL
                        && platform != SHARE_MEDIA.FLICKR
                        && platform != SHARE_MEDIA.FOURSQUARE
                        && platform != SHARE_MEDIA.TUMBLR
                        && platform != SHARE_MEDIA.POCKET
                        && platform != SHARE_MEDIA.PINTEREST

                        && platform != SHARE_MEDIA.INSTAGRAM
                        && platform != SHARE_MEDIA.GOOGLEPLUS
                        && platform != SHARE_MEDIA.YNOTE
                        && platform != SHARE_MEDIA.EVERNOTE) {
                    Toast.makeText(mActivity.get(),   " 分享成功啦", Toast.LENGTH_SHORT).show();
                }

            }
        }
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                    && platform != SHARE_MEDIA.EMAIL
                    && platform != SHARE_MEDIA.FLICKR
                    && platform != SHARE_MEDIA.FOURSQUARE
                    && platform != SHARE_MEDIA.TUMBLR
                    && platform != SHARE_MEDIA.POCKET
                    && platform != SHARE_MEDIA.PINTEREST

                    && platform != SHARE_MEDIA.INSTAGRAM
                    && platform != SHARE_MEDIA.GOOGLEPLUS
                    && platform != SHARE_MEDIA.YNOTE
                    && platform != SHARE_MEDIA.EVERNOTE) {
                Toast.makeText(mActivity.get(),  " 分享失败啦", Toast.LENGTH_SHORT).show();
                if (t != null) {
                    Log.d("throw", "throw:" + t.getMessage());
                }
            }

        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {

            Toast.makeText(mActivity.get(), " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    }

    protected void initNavigationBar() {
        RelativeLayout llNavBar = (RelativeLayout) this.findViewById(R.id.navigation_bar);
        if (llNavBar != null) {
            LinearLayout llBack = (LinearLayout) this.findViewById(R.id.ll_back);
            llBack.setVisibility(View.VISIBLE);
            llBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    goback();
                }
            });
        }
        setTitle(mTitle);
    }

    public void goback() {
        if(mWebFragment!=null){
            if ((mWebFragment).canGoBack()) {
                String url =  mWebFragment.getWebView().getUrl();
                LogUtil.i(TAG,"url:"+url);
                mWebFragment.getWebView().evaluateJavascript("javascript:backToURL()", new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String value) {
                        if(TextUtils.isEmpty(value) || "null".equals(value)){
                            (mWebFragment).goBack();// 返回前一个页面
                        }else{
                            if(mWebFragment.getWebView()!=null)
                                mWebFragment.setNeedClearHistory(true);
                            try {
                                int s = value.length();
                                String url = value.substring(1, s - 1);
                                mWebFragment.getWebView().loadUrl(url);
                            } catch (Exception e) {
                                (mWebFragment).goBack();// 返回前一个页面
                            }
                        }
                        if(isShare){
                            isShare =false;
                            setShareGone();
                        }
                    }
                });
            }else{
                finish();
            }
        }
    }

    /**
     * 将头部隐藏
     */
    public void setTopBarGone(){
        this.findViewById(R.id.navigation_bar).setVisibility(View.GONE);
    }

    public void setTopBarVisible(){
        this.findViewById(R.id.navigation_bar).setVisibility(View.VISIBLE);
    }

    private void setShareGone(){
        TextView tvShare = getTextView();
        tvShare.setVisibility(View.GONE);
    }

    @AfterPermissionGranted(REQUEST_PERMISSION_CAMERA)
    public void requestPermissionsCamera() {
        String[] perms = {Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(getContext(), perms)) {
            mWebFragment.toCamera();
        } else {
            EasyPermissions.requestPermissions(this, "app需要相机权限",
                    REQUEST_PERMISSION_CAMERA, perms);
        }
    }

    @AfterPermissionGranted(PERMISSION_READ_WRITE_EXTERNAL_STORAGE)
    public void readWritePermissions() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(getContext(), perms)) {
            ShareBoardConfig config = new ShareBoardConfig();
            config.setMenuItemBackgroundShape(ShareBoardConfig.BG_SHAPE_NONE);
            mShareAction.open(config);
            if(isGoodsShare){
                addTopView();
            }
        } else {
            EasyPermissions.requestPermissions(this, "您需要获取读写权限",
                    PERMISSION_READ_WRITE_EXTERNAL_STORAGE, perms);
        }
    }

    private void addTopView() {
        try {
            Class<?> shareActionClass = Class.forName("com.umeng.socialize.ShareAction");
            Field shareBoardField = shareActionClass.getDeclaredField("mShareBoard");
            shareBoardField.setAccessible(true);
            ShareBoard shareBoard = (ShareBoard) shareBoardField.get(mShareAction);
            LinearLayout ll = (LinearLayout) shareBoard.getContentView();
           // ll.addView();
            View topView = View.inflate(getContext(),R.layout.share_top_view,null);
            TextView text = topView.findViewById(R.id.sharp_top_text);
            text.setText(shareTopText);
            ll.addView(topView,0);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
